<?php

namespace control;

/*
*角色类
*/

class roleClass extends adIndexClass
{
    private const title = '角色类';
    private const page  = 'role';
    private static array $powerAllSelf = [];


    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $html = $this->tableShow([
            [
                [
                    L('role.home.name')    => text(array("name" => "name")),
                    L('log.home.powerOne') => select(["name" => "powerOne", "title" => "全部", "option" => array_keys($this->powerAll), "change" => "getPowerTwo"]),
                    L('log.home.powerTwo') => select(["name" => "powerTwo", "title" => "全部", "change" => "getPowerThree"]),
                ],
                [
                    L('role.home.powerThree') => select(["name" => "powerThree", "title" => "全部", "change" => "getPowerFour"]),
                    '四级导航'                    => select(["name" => "powerFour", "title" => "全部"]),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }


    /*列表页-查询条件*/
    public function home()
    {
        $html   = $this->homeOptions(false);
        $button = "";
        if ($this->power("role", "edit")) {
            $button .= "
			<span class='spanButton' onclick=\"layer('role','edit',{})\">" . L('setting.table.new_role') . "</span>
			<span onclick=\"pasWarn('listForm','role','delete')\" class='spanButton'>" . L('setting.table.delAll') . "</span>
			";
        }
        //返回
        $html = $this->search($html, layout: 'pop', toolButton: $button);
        return $this->homeFun($html);
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'name'  => [
                        'name'  => L('setting.table.jsmc'),
                        'width' => 400,
                    ],
                    'power' => [
                        'name'  => L('setting.table.zuozhe_xian'),
                        'width' => 900,
                    ],
                    'list'  => [
                        'name'  => L('setting.table.pai_xu_hao'),
                        'width' => 200,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询结果*/
    public function homeSearch()
    {
        $powerSearch = $or = '';
        //like查询数组
        $like = [
            "name"  => $this->post('name'),//角色名称
            "power" => $this->post('powerFour')
        ];
        //权限查询
        $powerOne   = $this->post('powerOne');    //一级导航
        $powerTwo   = $this->post('powerTwo');    //二级导航
        $powerThree = $this->post('powerThree');  //三级导航
        if ($powerOne) {
            // 二级不存在
            if (!$powerTwo) {
                $and = "";
                foreach ($this->powerAll[$powerOne] as $twoArray) {
                    foreach ($twoArray as $threeArray) {
                        foreach ($threeArray as $key => $value) {
                            if ($and) {
                                $or = " or ";
                            }
                            $and .= $or . " power like '%\"$key\":%' ";
                        }
                    }
                }
                $powerSearch = " and ( " . $and . " ) ";
            } elseif (!$powerThree) {
                // 二级存在，判断三级是否存在
                $data = [];
                $and  = "";
                foreach ($this->powerAll[$powerOne][$powerTwo] as $value) {
                    $data = array_merge($data, array_keys($value));
                }
                foreach ($data as $value) {
                    if ($and) {
                        $or = " or ";
                    }
                    $and .= $or . " power like '%\"$value\":%' ";
                }
                $powerSearch = " and ( " . $and . " ) ";
            } else {
                $and  = "";
                $data = array_keys($this->powerAll[$powerOne][$powerTwo][$powerThree]);
                foreach ($data as $value) {
                    if ($and) {
                        $or = " or ";
                    }
                    $and .= $or . " power like '%\"$value\":%' ";
                }
                $powerSearch = " and ( " . $and . " ) ";
            }
        }
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'list',
            "sort"   => $this->post('list_sort') ?: "asc",
            "array"  => array(),
        ));
        //获取查询结果
        $where = search(["like" => $like]) . $powerSearch;
        $page  = $this->page(array("table" => "role", "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "roleId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = $this->dominate(array(
                "box"    => array("name" => "roleId", "value" => $array['id']),
                "detail" => array("title" => L('setting.table.jsxq'), "click" => "newIframe('" . L('setting.table.jsxq') . "','" . root . "control/adIndex.html?cla=role&fun=detail&id=" . $array['id'] . "')"),
            ));
            $liButton[] = $dominate;
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'power':
                        //权限
                        $power    = "";
                        $powerNow = json_decode($array['power'], true);
                        if ($powerThree) {
                            foreach ($this->powerAll[$powerOne][$powerTwo][$powerThree] as $threeKey => $threeArray) {
                                if (isset($powerNow[$threeKey]) && count(array_intersect(array_keys($threeArray), (array)$powerNow[$threeKey])) > 0) {
                                    $power .= $threeArray['name'] . "；";
                                }
                            }
                        } elseif ($powerTwo) {
                            foreach ($this->powerAll[$powerOne][$powerTwo] as $twoArray) {
                                foreach ($twoArray as $menuTwoName => $menuTwoValue) {
                                    if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                                        $power .= $menuTwoValue['name'] . "；";
                                    }
                                }
                            }
                        } elseif ($powerOne) {
                            foreach ($this->powerAll[$powerOne] as $oneKey => $twoArray) {
                                foreach ($twoArray as $threeArray) {
                                    foreach ($threeArray as $menuTwoName => $menuTwoValue) {
                                        if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                                            $power .= $menuTwoValue['name'] . "；";
                                        }
                                    }
                                }
                            }
                        } else {
                            foreach ($this->powerAll as $oneArray) {
                                foreach ($oneArray as $twoArray) {
                                    foreach ($twoArray as $threeArray) {
                                        foreach ($threeArray as $menuTwoName => $menuTwoValue) {
                                            if (isset($powerNow[$menuTwoName]) && count(array_intersect(array_keys($menuTwoValue), (array)$powerNow[$menuTwoName])) > 0) {
                                                $power .= $menuTwoValue['name'] . "；";
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        $row[] = $power;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /*编辑角色档案-弹出层*/
    public function edit()
    {
        $id = $this->post('id');
        //数据查询
        $role = query("role", " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . L('setting.table.jsmc') . "："       => text(["name" => "name", "value" => $role['name'],]),
                    must . L('setting.table.pai_xu_hao') . "：" => text(["name" => "list", "value" => $role['list'],]),
                ),
                array(
                    must . L('setting.table.bei_zhu') . "：" => textarea(["name" => "text", "value" => $role['text']]),
                ),
            ),
        ));
        //返回
        return $this->layer(["title" => L('setting.table.bian_ji_jiao_se'), "height" => 270, "html" => $html]);
    }

    /*角色详情页~基本信息-异步处理*/
    public function editEdit()
    {
        $id = $this->post('id') ?: suiji();
        //赋值
        $field = array(
            "name"       => $this->post('name'),//角色名称
            "list"       => $this->post('list'),//排序号
            "text"       => $this->post('text'),//职位描述
            "updateTime" => date("Y-m-d H:i:s"),//更新时间
        );
        $role  = query("role", " id = '" . $id . "' ");
        //判断
        if (!$this->power("role", "edit")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($field['name'])) {
            $json['warn'] = L('setting.table.qtxjsmc');
        } elseif (sqlNum("role", " name = '$field[name]' and id != '" . $this->post('id') . "' ") > 0) {
            $json['warn'] = L('setting.table.gjsyjcz');
        } elseif (empty($field['list'])) {
            $json['warn'] = L('setting.table.qtxpxh');
        } elseif (preg_match(checkInteger, $field['list']) == 0) {
            $json['warn'] = L('setting.table.pxhbxwzzs');
        } elseif (empty($field['text'])) {
            $json['warn'] = L('setting.table.qjymsgjs');
        }elseif (empty($role['id'])) {
            $field        = array_merge($field, array("id" => $id, "time" => date("Y-m-d H:i:s")));
            $json['warn'] = static::insert(["table" => "role", "field" => $field]);
        } else {
            $json['warn'] = static::update(["table" => "role", "field" => $field, "where" => "id = '" . $this->post('id') . "'"]);
        }
        if (in_array($json['warn'], ["新增成功", "更新成功"])) {
            //添加日志
            $type = mb_substr($json['warn'], 0, 2, 'utf-8');
            $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $field['name']], L('setting.table.role_edit_text'));
            $this->logText(["type" => "role", "text" => $text]);
            //提示
            $_SESSION['warn'] = $json['warn'];
            $json['warn']     = 2;
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-角色详情页*/
    public function detail()
    {
        $role = query("role", " id = '" . $this->get('id') . "' ");
        if (!$this->power("role", "see")) {
            $html = L('setting.table.nmzjsckzx');
        } elseif (empty($this->get('id'))) {
            $html = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $html = L('setting.table.wzdcjs');
        } else {
            $data = [
                "id"   => $role['id'],
                "name" => $role['name'],
                "menu" => [
                    "detail" => '权限设置',
                    "info"   => '基本信息',
                ],
            ];
            //生成表单
            $data['html'] = $this->style().$this->tabPower().$this->js();
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    private function style(){
        return <<<EOT
<style>
   /***默认不展开样式***/
</style>
EOT;
    }


    public function info()
    {
        //按钮
        $role   = query("role", " id = '" . $this->get('id') . "' ");
        $button = [];
        if ($this->power("role", "edit")) {
            $button[] = array(
                "name"  => L('setting.table.edit'),
                "type"  => "弹出层",
                "cla"   => "role",
                "fun"   => "edit",
                "post"  => array("id" => $role['id']),
                'style' => 'li-btn-blue-bg',
            );
            $button[] = array(
                "name" => L('setting.table.fu_zhi'),
                "type" => "弹出层",
                "cla"  => "role",
                "fun"  => "copy",
                "post" => array("id" => $role['id']),
            );
        }
        //生成表单
        $button = $this->tableShowButton($button);
        $table = $this->tableShow(array(
            L('setting.table.jiao_se_dang_an') => array(
                array(
                    L('setting.table.jsmc')       => $role['name'],
                    L('setting.table.pai_xu_hao') => $role['list'],
                    L('setting.table.roleId')     => $role['id'],
                    L('setting.table.gxsj') => $role['updateTime'],
                ),
                array(
                    L('setting.table.cjsj') => $role['time'],
                ),
                array(
                    L('setting.table.bei_zhu') => pre($role['text']),
                ),
            ),
        ));
        $json['html'] = "
		<div class='tab-box'>
		        <div class='tab-button'>" . $button . "</div>
		        <div class='tab-content'>
			    " . $table . clear . "
			    </div>
        </div>";
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function tabPower()
    {
//        $id = $this->get('id');
        self::$powerAllSelf = $this->powerAllLang;
        //返回
        $rightHtml       = $this->homeRight();
        $search          = "<div class='container-left-search-parent flex-box'>
                                ".text(["name" => 'name', 'title' => "搜索", 'class' => 'container-left-search', 'value' => ''])."
                                <i class='container-left-search-ico' onclick=\"search_left()\"></i>
                                <span class='search-count'>0/0</span>
                            </div>";
        $option['click'] = "replaceContent(this, '" . self::page . "')";
        $option['id']    = $this->get('id');
        $all             = self::getDepartmentAll($option);
        $html            = <<<EOT
        <div class="container-main">
            <div class="container-left " id="container-left">
                {$search}
                <div class="classify-area">
                    {$all}
                </div>
            </div>
            <div class="container-right " id="container-detail">
               {$rightHtml}
            </div>
        </div>
<style>
.width15{width:15px;height: 15px;cursor: pointer}
.tab-content {overflow: hidden;}
.container-main .container-right {height: calc(100vh - 110px);display: block;overflow: auto;min-height: unset;padding: 10px;}
.container-main .container-left .classify-area {height: calc(100vh - 150px);}
</style>
EOT;
        //返回
        return $html;
//        return json_encode($json, 320);
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson(): bool|string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRight()
    {
        $menuOnePost   = $this->post('menuOne');
        $menuTwoPost   = $this->post('menuTwo');
        $menuThreePost = $this->post('menuThree');
        $menuFourPost  = $this->post('menuFour');
        $result        = $this->powerAllLang;
        $html          = '';
        $line          = '';
        $role          = query("role", " id = '" . $this->get('id') . "' ");
        $power         = json_decode($role['power'], true);
        foreach ($result as $menuOneKey => $menuOne) {
            if ($menuOnePost && $menuOnePost != $menuOneKey) {
                continue;
            }
            foreach ($menuOne as $menuTwoKey => $menuTwo) {
                if ($menuTwoPost && $menuTwoPost != $menuTwoKey) {
                    continue;
                }
                foreach ($menuTwo as $menuThreeKey => $menuThree) {
                    if ($menuThreePost && $menuThreePost != $menuThreeKey) {
                        continue;
                    }
                    $box      = '';
                    $checkAll = "checked";
                    foreach ($menuThree as $menuFourKey => $menuFour) {
                        $name = $menuFour['name'];
                        unset($menuFour['name']);
                        unset($menuFour['cla']);
                        unset($menuFour['fun']);
                        $checkedTemp = $power[$menuFourKey] ?? '';
                        $box         .= "<p data-four='$menuFourKey'>" . checkbox(array("name" => "power[" . $menuFourKey . "]", 'other' => "data-power='$menuFourKey' onclick='roleSet(this)'", "value" => $menuFour, "checked" => $checkedTemp, "title" => $name)) . "</p>";
                        if (array_keys($menuFour) != $checkedTemp) {
                            $checkAll = "";
                        }
                    }
                    $navigateBar = $menuOneKey . '>' . $menuTwoKey . '>' . $menuThreeKey;
                    $html        .= "
				<div class='box " . $line . "'>
					<p data-one='$menuOneKey' data-two='$menuTwoKey' data-three='$menuThreeKey'><label class='checkbox' ><input type='checkbox' onchange=\"powerCheckAll(this)\" " . $checkAll . "><span></span>\n $navigateBar</label></p>
					" . $box . "
				</div>";
                    $line        = "line";//分隔线
                }
            }
        }
        return "<form name='powerForm'>" . $html . hidden(['name' => 'id', 'value' => $this->get('id')]) . "</form>";
    }


    /**
     * 左侧搜索框
     *
     * @return string
     */
//    public function getContainerLeftJson(): string
//    {
//        $option['click'] = "replaceContent(this, '" . self::page . "')";
//        $json['html']    = self::getDepartmentAll($option);
//        return json_encode($json, 320);
//    }

    public static function getDepartmentAll($data = []): string
    {
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? "replaceContent(this,'" . self::page . "')";
        $role          = query("role", " id = '" . $data['id'] . "' ");
        $power         = json_decode($role['power'], true);
        // 结果
        $result = self::$powerAllSelf;
        $style  = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp   = "<input class='width15' name='allBoxs' type='checkbox' onclick='chooseAll(this)'><span class='cursor linght-blue-font' onclick=\"{$data['click']}\">&nbsp;全选</span><ul style='margin-left: 14px' {$style} {$data['where']}>";
        $ico    = "<input type='checkbox' class='width15' onclick=\"checkAllBox(this)\">";
        foreach ($result as $menuOneKey => $menuOne) {
            $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
            $temp  .= "<li class='arrow-li' data-level='one' data-menuone='$menuOneKey'  data-id='$menuOneKey' title='$menuOneKey' onclick=\"{$data['click']}\">$arrow<span class='textcontent linght-blue-font'>$ico $menuOneKey</span></li>";
            $temp  .= "<ul class='child-node' pid='$menuOneKey'>";
            foreach ($menuOne as $menuTwoKey => $menuTwo) {
                $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                $temp  .= "<li class='arrow-li' data-level='two' data-menuone='$menuOneKey' data-menutwo='$menuTwoKey'  data-id='$menuTwoKey' title='$menuTwoKey' onclick=\"{$data['click']}\">$arrow<span class='textcontent linght-blue-font'>$ico $menuTwoKey</span></li>";
                $temp  .= "<ul class='child-node' pid='$menuTwoKey'>";
                foreach ($menuTwo as $menuThreeKey => $menuThree) {
                    $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                    $temp  .= "<li class='arrow-li' data-level='three' data-menuone='$menuOneKey' data-menutwo='$menuTwoKey' data-menuthree='$menuThreeKey'  data-id='$menuThreeKey' title='$menuThreeKey' onclick=\"{$data['click']}\">$arrow<span class='textcontent linght-blue-font'>$ico $menuThreeKey</span></li>";
                    $temp  .= "<ul class='child-node' pid='$menuThreeKey'>";
                    foreach ($menuThree as $menuFourKey => $menuFour) {
                        $menuFourTemp = $menuFour;
                        unset($menuFourTemp['name']);
                        unset($menuFourTemp['cla']);
                        unset($menuFourTemp['fun']);
                        $checkAll    = "checked";
                        $checkedTemp = $power[$menuFourKey] ?? '';
                        if (array_keys($menuFourTemp) != $checkedTemp) {
                            $checkAll = "";
                        }
                        $ico  = "<input type='checkbox' class='width15' $checkAll onclick=\"checkAllBox(this)\">";
                        $temp .= "<li class='arrow-no-li' data-level='four' data-menuone='$menuOneKey' data-menutwo='$menuTwoKey' data-menuthree='$menuThreeKey' data-menufour='$menuFourKey'  data-id='$menuFour[name]' title='$menuFour[name]' ><span class='textcontent'>$ico $menuFour[name]</span></li>";
                    }
                    $ico  = "<input type='checkbox' class='width15' onclick=\"checkAllBox(this)\">";
                    $temp .= '</ul>';
                }
                $temp .= '</ul>';
            }
            $temp .= '</ul>';
        }
        $temp .= '</ul>';
        return $temp;
    }

    /**
     * JS
     */
    private function js(): string
    {
        return <<<eof
<script>
$(function() {
  leftCheckBoxInit();
  search_left();
})
/**
* 左边菜单初始化
* 
* */
function leftCheckBoxInit(){
  
    let allChecked = true;
    let menuOne='';
    let menuTwo='';
    let menuThree='';
    //三级
    $("#container-left [data-level='three']").each(function() {
        allChecked = true;
        menuOne = $(this).data('menuone');
        menuTwo = $(this).data('menutwo');
        menuThree = $(this).data('menuthree');
        $("[data-level='four'][data-menuone='"+menuOne+"'][data-menutwo='"+menuTwo+"'][data-menuthree='"+menuThree+"']").find(":checkbox").each(function() {
         if (!$(this).prop('checked')) {
            allChecked = false;
          }
        })
       $(this).find(":checkbox").prop('checked', allChecked);
    })
     //二级
     $("#container-left [data-level='two']").each(function() {
        allChecked = true;
        menuOne = $(this).data('menuone');
        menuTwo = $(this).data('menutwo');
        $("[data-level='three'][data-menuone='"+menuOne+"'][data-menutwo='"+menuTwo+"']").find(":checkbox").each(function() {
         if (!$(this).prop('checked')) {
            allChecked = false;
          }
        })
       $(this).find(":checkbox").prop('checked', allChecked);
    })
    //一级
    $("#container-left [data-level='one']").each(function() {
        allChecked = true;
        menuOne = $(this).data('menuone');
        $("[data-level='two'][data-menuone='"+menuOne+"']").find(":checkbox").each(function() {
         if (!$(this).prop('checked')) {
            allChecked = false;
          }
        })
       $(this).find(":checkbox").prop('checked', allChecked);
    })
    //全选
      allChecked = true;
    $("#container-left [data-level='one']").find(":checkbox").each(function() {
        if (!$(this).prop('checked')) {
            allChecked = false;
          }
    })
    $("[name='allBoxs']").prop('checked',allChecked)
}
function powerCheckAll(obj) {
    var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parents(".box").find(":checkbox").prop('checked', bool);
    if (bool) {
        commitPower();
    }else{
        removePower();
    }
    $(obj).parents(".box").find("[data-four]").each(function() {
        //左边按钮控制
        $(".classify-area").find("[data-menufour='"+$(this).data('four')+"']").find('input[type=checkbox]').prop('checked', bool);
    });
    leftCheckBoxInit();
}
function removePower(form='powerForm'){
      let con = setTimeout(function (){
        $("#loading", window.top.document).hide();
    },15000);
        let power = {};
        $("[name=" +form + "] input[data-power]:not(:checked)").each(function() {
            let name = $(this).data('power');
             if (power[name]) {
                   power[name].push($(this).val());
             }else{
                  power[name] = [$(this).val()];
             }
        })
        let id = $("[name=" +form + "] input[name='id']").val();
        //异步提交数据
        $.post(root+'control/adIndex.html?cla=role&fun=powerRemoveEdit',{jsonData:JSON.stringify(power),id:id}, function (data) {
            if (data.warn === 2) {
                warn('修改成功')
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
}
function checkboxAll(obj) {
    var name = $(obj).val();
    let bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    $(obj).parent().siblings("label").children("[name='" + name + "\[\]']").prop('checked', bool);
    
    let parent = $(obj).parent().parent().parent();
     menuThreeIsAllChecked(parent); 
     if (bool) {
        commitPower();
    }else{
        removePower();
    }
    let power = $(obj).parent().parent().data('four');
      //左边按钮控制
    $(".classify-area").find("[data-menufour='"+power+"']").find('input[type=checkbox]').prop('checked', bool);
    leftCheckBoxInit();
}
function roleSet(e){
    let parent = $(e).parent().parent().parent();
    let parentFour = $(e).parent().parent();
    let power = $(e).data('power');
    let  allChecked = true;
    parentFour.find("[data-power]").each(function() {
        if (!$(this).prop('checked')) {
            allChecked = false;
          }
    })
    //权限前面的按钮
    parentFour.find("[name='power["+power+"]CheckAll']").prop('checked', allChecked);
    //左边按钮控制
    $(".classify-area").find("[data-menufour='"+power+"']").find('input[type=checkbox]').prop('checked', allChecked);
    leftCheckBoxInit();
    menuThreeIsAllChecked(parent); 
    if ($(e).prop('checked')){
        commitPower();
    }else{
        removePower();
    }
}

function menuThreeIsAllChecked(parent){
    let parentCheckbox=parent.find("[data-three]").find('input[type=checkbox]');
    let dataFour = '';
    let allChecked = true;
    parent.find("[data-four]").each(function() {
        dataFour = $(this).data('four');
        if ($(this).find("input[name='power["+dataFour+"]CheckAll']").prop('checked') == false){
            allChecked = false;
        }
    });
    //三级菜单权限按钮反显
    parentCheckbox.prop('checked', allChecked);
}

var searchKeyWord = '';
/**
 * 分类树形导航搜索
 */
function search_left() {
    let keyword = $('#container-left input[name=name]').val();
    searchKeyWord = keyword;
    //回车查询，关键词一样，则一直往下定位
    findMatches(keyword, '.container-left li > .textcontent')
}
 $(window).keydown(function (event) {
        let keyword = $('#container-left input[name=name]').val();
        if (event.which === 13) {
            if (searchKeyWord && searchKeyWord === keyword){
                findNextMatch();
            }else{
                search_left();
            }
        }
    })
function chooseAll(obj){
    var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    if (bool){
        leftPowerAddEdit(null,null,null,null);
    }else{
        leftPowerRemoveEdit(null,null,null,null);
    }
    $(obj).parent().find(":checkbox").prop('checked', bool);
    $(".box").find(":checkbox").prop('checked', bool);
}

function checkAllBox(obj){
      var bool = false;
    if ($(obj).prop("checked")) {
        bool = true;
    }
    let parent = $(obj).parent().parent();
    let id = parent.data('id');
    parent.next("[pid='"+id+"']").find(":checkbox").prop('checked', bool);
      let menuOne = parent.data('menuone');
      let menuTwo = parent.data('menutwo');
      let menuThree = parent.data('menuthree');
       let menuFour = parent.data('menufour');
       if (menuFour){
           //点四级菜单
           $("[data-four='"+menuFour+"']").find(":checkbox").prop('checked', bool);
       }else if(menuThree){
           //点三级菜单
           $("[data-one='"+menuOne+"'][data-two='"+menuTwo+"'][data-three='"+menuThree+"']").find(":checkbox").each(function() {
                $(this).prop('checked', bool)
                $(this).parents(".box").find(":checkbox").prop('checked', bool);
           });
       }else if(menuTwo){
             //点二级菜单
            $("[data-one='"+menuOne+"'][data-two='"+menuTwo+"']").find(":checkbox").each(function() {
                $(this).prop('checked', bool)
                $(this).parents(".box").find(":checkbox").prop('checked', bool);
           });
       }else if(menuOne){
             //点一级菜单
           $("[data-one='"+menuOne+"']").find(":checkbox").each(function() {
              $(this).prop('checked', bool)
              $(this).parents(".box").find(":checkbox").prop('checked', bool);
           });
       }
      if (bool){
           leftPowerAddEdit(menuOne,menuTwo,menuThree,menuFour);
      }else{
           leftPowerRemoveEdit(menuOne,menuTwo,menuThree,menuFour);
      }
       leftCheckBoxInit();
       window.event.stopPropagation();//阻止事件冒泡
}

function leftPowerAddEdit(menuOne,menuTwo,menuThree,menuFour){
   let id = $("[name='powerForm'] input[name='id']").val();
           //异步提交数据
    $.post(root+'control/adIndex.html?cla=role&fun=leftPowerEdit',{type:'add',menuOne:menuOne,menuTwo:menuTwo,menuThree:menuThree,menuFour:menuFour,id:id}, function (data) {
        if (data.warn !== 2) {
            warn(data.warn, 'error');
        }else{
            warn('修改成功');
        }
    }, "json");
}

function leftPowerRemoveEdit(menuOne,menuTwo,menuThree,menuFour){
   let id = $("[name='powerForm'] input[name='id']").val();
           //异步提交数据
    $.post(root+'control/adIndex.html?cla=role&fun=leftPowerEdit',{type:'remove',menuOne:menuOne,menuTwo:menuTwo,menuThree:menuThree,menuFour:menuFour,id:id}, function (data) {
        if (data.warn !== 2) {
            warn(data.warn, 'error');
        }else{
            warn('修改成功');
        }
    }, "json");
}

function commitPower(form='powerForm'){
      let con = setTimeout(function (){
        $("#loading", window.top.document).hide();
    },15000);
        let power = {};
        $("[name=" +form + "] input[data-power]:checked").each(function() {
            let name = $(this).data('power');
             if (power[name]) {
                   power[name].push($(this).val());
             }else{
                  power[name] = [$(this).val()];
             }
        })
        let id = $("[name=" +form + "] input[name='id']").val();
        //异步提交数据
        $.post(root+'control/adIndex.html?cla=role&fun=powerChangeEdit',{jsonData:JSON.stringify(power),id:id}, function (data) {
            if (data.warn === 2) {
                warn('修改成功');
            } else {
                warn(data.warn, 'error');
            }
            $("#loading", window.top.document).hide();
            clearTimeout(con);
        }, "json");
}

</script>
eof. $this->jsTwo();
    }

    private function jsTwo()
    {
        return <<<eof
<script>
/**
 * 分类树形导航搜索，匹配所有关键字
 * @param keyword 关键字
 * @param querySelectorAll 搜索节点，例如：.container-left li > .textcontent
 * @returns {[]}
 */
function findMatches(keyword, querySelectorAll, scrollingArea = '.classify-area') {
    let matches = [];
    let elements = $(querySelectorAll);
    scrollingArea = $(scrollingArea);
    let ico = '';
    // 清空搜索关键字
    if(elements.find('.keyword-match').length > 0) {
        //默认展示第一级
        scrollingArea.find('li').show()
        scrollingArea.children().children("[data-level='one']").show()
        scrollingArea.find('.child-node').hide();
        scrollingArea.find('.arrow').css({
            'transform': 'rotate(90deg)',
        })
        // 清空所有搜索
        elements.each(function () {
            let element = $(this);
            let htmlContent = element.html();
            let  select = element.find(':checkbox');
            let plainText = htmlContent.replace(/<em class="keyword-match( now-keyword-match)?">|<\/em>/g, '');
            element.html(plainText);
            var selectRes = element.find(':checkbox');
            for (var i = 0; i <select.length ; i++) {
                $(selectRes[i]).prop('checked',$(select[i]).prop('checked'));
            }
        });
    }
    
    // 重新匹配搜索
    if (keyword) {
        keyword = keyword.trim();
        scrollingArea.find('.child-node').hide();
        scrollingArea.find('.arrow-li').hide();
        scrollingArea.find('.arrow-no-li').hide();
        elements.each(function () {
            let element = $(this);
            let prevli = element.parents('.child-node').prev()

            let textContent = element.text();
            let regex = new RegExp(keyword, 'gi');
            
            let checkedBool = element.parent().find(":checkbox").prop('checked');
            
            if (textContent.includes(keyword)) {
                 ico = "<input type='checkbox' class='width15' onclick='checkAllBox(this)'>";
                if (checkedBool){
                     ico = "<input type='checkbox' checked class='width15' onclick='checkAllBox(this)'>";
                }
                let highlightedText = textContent.replace(regex, `<em class="keyword-match">$&</em>`);
                element.html(ico+highlightedText);
                matches.push(this);
                //展开匹配项
                element.parents('.arrow-no-li').show()
                element.parents('.arrow-li').show()
                prevli.show()
                element.parents('.child-node').css('display', 'block')
                prevli.find('.arrow').css({
                    'transform': 'rotate(180deg)',
                })
            }
        });
        if (matches.length > 0) {
            let text = '1' + '/'+ matches.length
            $(".search-count").html(text);
            matches[0].scrollIntoView({behavior: "smooth", block: "nearest", inline: "center"});
            $(matches[0]).find('.keyword-match').addClass('now-keyword-match');
        }else{
            let text = '0' + '/'+ matches.length
            $(".search-count").html(text);
        }
    }else{
        $(".search-count").html('0/0');
    }

    return matches;
}

/**
 * 获取右边内容
 * @param obj
 * @param cla
 */
function replaceContent(obj, cla) {
    let id = $("[name='id']").val();
     let menuOne = $(obj).data('menuone');
      let menuTwo = $(obj).data('menutwo');
       let menuThree = $(obj).data('menuthree');
       let menuFour = $(obj).data('menufour');
    let api = root + 'control/adIndex.html?cla=' + cla + '&fun=homeRightJson&id='+id;
    if (id.length > 0) {
        $("#container-left li").removeClass('active');
        $(obj).addClass('active')
        $.post(api, {
            menuOne:menuOne,
            menuTwo:menuTwo,
            menuThree:menuThree,
            menuFour:menuFour
        }, function (data) {
            $('#container-detail').html(data.html)
        }, "json");
    }
}

$.fn.serializeJson = function() {
        var serializeObj = {};
        var array = this.serializeArray();
        $(array).each(function() {
            if (serializeObj[this.name]) {
                if ($.isArray(serializeObj[this.name])) {
                    serializeObj[this.name].push(this.value);
                } else {
                    serializeObj[this.name] = [serializeObj[this.name], this.value];
                }
            } else {
                serializeObj[this.name] = this.value;
            }
        });
        return serializeObj;
    };
</script>
eof;

    }

    /**
     * 复制
     */
    public function copy()
    {
        $info = query("role", " id = '" . $this->post('id') . "' ");
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($this->post('id'))) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } else {
            $field        = [
                'id'         => self::getId(),
                'name'       => $info['name'] . ' - ' . L('setting.table.copy'),
                'list'       => $info['list'] + 1,
                'text'       => $info['text'],
                'power'      => $info['power'],
                'updateTime' => $this->time,
                'time'       => $this->time,
            ];
            $json['warn'] = static::insert([
                'table' => 'role',
                'field' => $field,
            ]);
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $info['name']], L('setting.table.copy_text'));
                $this->logText(array("type" => "role", "text" => $text));
                //提示
                $_SESSION['warn'] = L('setting.table.fzzxcg');
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=role&fun=detail&id=" . $field['id'];
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }


    /**
     * 获取两个字符中间的字符串
     *
     * @param $input
     * @param $start
     * @param $end
     * @return string
     */
    private function cutBetween($input, $start, $end): string
    {
        return substr($input, strlen($start) + strpos($input, $start), (strlen($input) - strpos($input, $end)) * (-1));
    }

    /**
     * 替换数组元素
     * @param $arrayA
     * @param $arrayB
     * @return mixed
     */
    public function replaceArrayElements($arrayA, $arrayB)
    {
        foreach ($arrayA as $key => $value) {
            $arrayB[$key] = $value;
        }
        return $arrayB;
    }

    /**
     * 查找并移除 从A中移除与B中相同的值
     * @param $arrayA
     * @param $arrayB
     * @return mixed
     */
    public function findAndRemove($arrayA, $arrayB)
    {
        foreach ($arrayB as $key => $value) {
            if (isset($arrayA[$key])) {
                $arrayA[$key] = array_diff($arrayA[$key], $value);
                if (empty($arrayA[$key])) {
                    unset($arrayA[$key]);
                } else {
                    $arrayA[$key] = array_values($arrayA[$key]);
                }
            }
        }
        return $arrayA;
    }

    /**
     * 左边菜单栏点击选择
     * @return false|string
     */
    public function leftPowerEdit()
    {
        $menuOnePost   = $this->post('menuOne');
        $menuTwoPost   = $this->post('menuTwo');
        $menuThreePost = $this->post('menuThree');
        $menuFourPost  = $this->post('menuFour');
        $type          = $this->post('type');
        $power         = [];
        foreach ($this->powerAll as $menuOneKey => $menuOne) {
            if ($menuOnePost && $menuOnePost != $menuOneKey) {
                continue;
            }
            foreach ($menuOne as $menuTwoKey => $menuTwo) {
                if ($menuTwoPost && $menuTwoPost != $menuTwoKey) {
                    continue;
                }
                foreach ($menuTwo as $menuThreeKey => $menuThree) {
                    if ($menuThreePost && $menuThreePost != $menuThreeKey) {
                        continue;
                    }
                    foreach ($menuThree as $menuFourKey => $menuFour) {
                        if ($menuFourPost && $menuFourPost != $menuFourKey) {
                            continue;
                        }
                        unset($menuFour['name']);
                        unset($menuFour['cla']);
                        unset($menuFour['fun']);
                        $power[$menuFourKey] = array_keys($menuFour);
                    }
                }
            }
        }
        if ($type == 'add')
            return $this->powerChangeEdit($power);
        else
            return $this->powerRemoveEdit($power);
    }

    /**
     * 取消权限
     * @return false|string
     * @throws \Exception
     */
    public function powerRemoveEdit($power = null)
    {
        $result['power'] = $power ?: json_decode($_POST['jsonData'], true);
        //{"department":["see","edit"],"job":["see","edit","del","import","export"]}
        $result['id'] = $this->post('id');
        $role         = query("role", " id = '" . $result['id'] . "' ");
        //判断
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($result['id'])) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } elseif (!isset($result['power']) || !is_array($result['power']) || empty($result['power'])) {
            $json['warn'] = L('setting.table.qgxxydzx');
        } else {
            $arrayReplace = json_decode($role['power'], true);
            $arrayReplace = $this->findAndRemove($arrayReplace, $result['power']);
            $json['warn'] = update(array(
                "table" => "role",
                "field" => array(
                    "power"      => json_encode($arrayReplace),
                    "updateTime" => date("Y-m-d H:i:s"),
                ),
                "where" => " id = '$role[id]' ",
            ));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                $json['warn'] = 2;
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }

    public function powerChangeEdit($power = null)
    {

        $result['power'] = $power ?: json_decode($_POST['jsonData'], true);
        //{"department":["see","edit"],"job":["see","edit","del","import","export"]}
        $result['id'] = $this->post('id');
        $role         = query("role", " id = '" . $result['id'] . "' ");
        //判断
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($result['id'])) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } elseif (!isset($result['power']) || !is_array($result['power']) || empty($result['power'])) {
            $json['warn'] = L('setting.table.qgxxydzx');
        } else {
            $arrayReplace = json_decode($role['power'], true);
            $arrayReplace = $this->replaceArrayElements($result['power'], $arrayReplace);
            $json['warn'] = update(array(
                "table" => "role",
                "field" => array(
                    "power"      => json_encode($arrayReplace),
                    "updateTime" => date("Y-m-d H:i:s"),
                ),
                "where" => " id = '$role[id]' ",
            ));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                $json['warn'] = 2;
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-详情页-权限设置-异步处理*/
    public function powerEdit()
    {
        $result['power'] = json_decode($_POST['jsonData'], true);
        $result['id']    = $this->post('id');
        $role            = query("role", " id = '" . $result['id'] . "' ");
        //判断
        if (!$this->power("role", "power")) {
            $json['warn'] = L('setting.table.nmzbjjsdzx');
        } elseif (empty($result['id'])) {
            $json['warn'] = L('setting.table.roleIdEmpty');
        } elseif (empty($role['id'])) {
            $json['warn'] = L('setting.table.wzdcjs');
        } elseif (!isset($result['power']) || !is_array($result['power']) || empty($result['power'])) {
            $json['warn'] = L('setting.table.qgxxydzx');
        } else {
            $json['warn'] = update(array(
                "table" => "role",
                "field" => array(
                    "power"      => json_encode($result['power']),
                    "updateTime" => date("Y-m-d H:i:s"),
                ),
                "where" => " id = '$role[id]' ",
            ));
            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}'], [$this->control['name'], $role['name']], L('setting.table.edit_text'));
                $this->logText(array("type" => "role", "text" => $text));
                //提示
                $_SESSION['warn'] = L('setting.table.zxszcg');
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=role&fun=detail&menu=tabPower&id=" . $role['id'];
            }
            //添加日志
        }
        //返回
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-删除角色*/
    public function delete()
    {
        if (!$this->power("role", "edit")) {
            $json['warn'] = L('setting.table.zxbz');
        } elseif (empty($this->post('roleId'))) {
            $json['warn'] = L('setting.table.nygjsdmzxzn');
        } elseif (empty($this->post('password'))) {
            $json['warn'] = L('setting.table.qsrdlmm');
        } elseif (verifyPwd($this->post('password'), self::$user['password']) === false) {
            $json['warn'] = L('setting.table.dlmmsrcw');
        } else {
            $x   = 0;
            $txt = "";
            foreach ($this->post('roleId') as $id) {
                //数据准备
                $role = query("role", " id = '$id'");
                if (sqlNum("user", " role like '%$id%' ") > 0) {
                    $txt .= str_replace(['{{name}}'], [$role['name']], L('setting.table.role_del_warn_one'));
                } elseif ($role['isDel']) {
                    $txt .= str_replace(['{{name}}'], [$role['name']], L('setting.table.role_del_warn_two'));
                } else {
                    //最后删除角色基本参数
                    delete(["table" => "role", "where" => " id = '$id' "]);
                    //返回
                    $txt .= $role['name'] . L('setting.table.sccg');
                    $x++;
                }
            }
            //添加记录
            $logText = str_replace(['{{staffName}}', '{{x}}'], [$this->control['name'], $x], L('setting.table.role_del_text')) . $txt;
            $this->logText(array("type" => "role", "text" => $logText));
            //返回
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('setting.table.role_del_msg'));
            $json['warn']     = 2;
        }
        //返回JSON
        return json_encode($json, 320);
    }

    /*行政人事-角色管理-根据一级导航返回二级导航*/
    public function getPowerName()
    {
        $field = $this->post('field') ?: 'name';
        $value = $this->post('value') ?: '';
        $name  = $this->post('name');
        $level = $this->post('level');
        if ($level == 3) {
            $json['res'] = getPowerFour($name, $value, $field);
        } elseif ($level == 2) {
            $json['res'] = getPowerThree($name, $value);
        } else {
            $json['res'] = getPowerTwo($name, $value);
        }
        return json_encode($json, 320);
    }
}
